import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tencent_cloud_chat_uikit/business_logic/view_models/tui_conversation_view_model.dart';
import 'package:xindong/common/xindong_common_vm.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/manager/network/xindong_networking.dart';
import 'package:xindong/manager/network/xindong_response.dart';
import 'package:xindong/manager/xindong_notice_ctr.dart';
import 'package:xindong/manager/xindong_tencent_singleton.dart';
import 'package:xindong/widgets/dialog/xindong_alert_options.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';
import 'package:tencent_cloud_chat_uikit/ui/controller/tim_uikit_conversation_controller.dart';

class XinDongLiaoTianClass {
  late V2TimConversation conversation;
  int? level;
  Map? customInfo;
}

class XinDongLiaoTianVM extends XinDongCommonVM {
  static XinDongLiaoTianVM get to => Get.find();
  final unreadCount = Rx(0);
  String nextSeq = "0";
  String loginUserId = "";
  String? currentConversationID = ""; // 当前正在聊天的会话ID，正在聊天的会话，未读数不统计，要注意设置后销毁，不然一直不统计未读数量
  List<XinDongLiaoTianClass> conversationList = [];
  V2TimConversation? serverConversation;
  List<String> signalMessageIds = [];

  XinDongLiaoTianVM({super.initialRefresh = false});

  // 清空数据
  void clear() {
    conversationList.clear();
    unreadCount.value = 0;
    serverConversation = null;
    currentConversationID = null;
    update();
  }

  // 请求加载会话列表
  Future<NetworkResponse> _requestLoadData({required String nextSeq, int count = 50}) async {
    isLoading = true;
    V2TimValueCallback<V2TimConversationResult> result = await TencentImSDKPlugin.v2TIMManager
        .getConversationManager()
        .getConversationList(count: count, nextSeq: nextSeq);
    Future.delayed(const Duration(milliseconds: 1000)).whenComplete(() => isLoading = false);
    return NetworkResponse(
      code: result.code == 0 && result.data != null ? XinDongServerStatus.success : result.code,
      msg: result.desc,
      data: result.data ?? V2TimConversationResult(),
    );
  }

  // 加载客服
  void loadData() async {
    V2TimValueCallback<V2TimConversation> result = await TencentImSDKPlugin.v2TIMManager
        .getConversationManager()
        .getConversation(conversationID: 'c2c_${XinDongTencentSingleton.instance.customerID}');
    if (result.code == 0 && result.data != null) {
      XinDongNoticeCtr.to.kefuCount = result.data?.unreadCount ?? 0;
      XinDongNoticeCtr.to.update();
      mDebugPrint("客服：${result.data?.unreadCount}");
    } else {
      mDebugPrint("客服：${result.desc}");
    }
  }

  // 加载用户信息
  // 1、刷新、加载更多时调用
  // 2、有新会话时调用
  loadUserFullInfo(List<V2TimConversation?> modelList) async {
    if (modelList.isEmpty) return;
    List<String> userIDList = modelList.map((e) => "${e?.userID}").toList();
    //获取用户资料
    V2TimValueCallback<List<V2TimUserFullInfo>> getUsersInfoRes =
        await TencentImSDKPlugin.v2TIMManager.getUsersInfo(userIDList: userIDList); //需要查询的用户id列表

    if (getUsersInfoRes.code == 0) {
      // 查询成功
      for (var model in conversationList) {
        final userInfo = getUsersInfoRes.data
            ?.firstWhere((element) => element.userID == model.conversation.userID, orElse: () => V2TimUserFullInfo());
        model.customInfo = userInfo?.customInfo;
        model.level = userInfo?.level;

        print("object mmmm ${userInfo?.toJson()}");
      }
      update();
    }
  }

  updateConversationFriendInfo(List<V2TimFriendInfo> friendInfoList) {
    if (friendInfoList.isNotEmpty && conversationList.isNotEmpty) {
      final friendInfo = friendInfoList.first;
      XinDongLiaoTianClass? model =
          conversationList.firstWhereOrNull((element) => element.conversation.userID == friendInfo.userID);
      if (model != null) {
        model.conversation.showName = friendInfo.friendRemark;
        update();
      }
    }
  }

  deleteConversationFriendInfo(List<String> userIdList) async {
    if (userIdList.isNotEmpty && conversationList.isNotEmpty) {
      final userID = userIdList.first;
      XinDongLiaoTianClass? model =
          conversationList.firstWhereOrNull((element) => element.conversation.userID == userID);
      if (model != null) {
        //获取用户资料
        V2TimValueCallback<List<V2TimUserFullInfo>> getUsersInfoRes =
            await TencentImSDKPlugin.v2TIMManager.getUsersInfo(userIDList: [userID]);
        if (getUsersInfoRes.code == 0 && getUsersInfoRes.data != null) {
          final userInfo = getUsersInfoRes.data!.first;
          model.conversation.showName = userInfo.nickName;
          update();
        }
      }
    }
  }

  @override
  void refreshData({NetworkResponse? object}) async {
    // 下面是IM消息列表
    nextSeq = "0";
    final object = await _requestLoadData(nextSeq: nextSeq);
    if (object.code == XinDongServerStatus.success) {
      V2TimConversationResult listClass = object.data ?? [];
      nextSeq = listClass.nextSeq!;
      hasMore = listClass.isFinished == false;
      // 清空数据
      conversationList.clear();
      updateConversationList(listClass.conversationList ?? [], isUpdate: false);
      loadUserFullInfo(listClass.conversationList ?? []);
    }
    // 最后调用父类方法，执行后续操作
    super.refreshData(object: object);
  }

  @override
  void loadMoreData({NetworkResponse? object}) async {
    if (hasMore == false) {
      refreshController.loadNoData();
      return;
    }
    final object = await _requestLoadData(nextSeq: nextSeq);
    if (object.code == XinDongServerStatus.success) {
      V2TimConversationResult listClass = object.data;
      nextSeq = listClass.nextSeq!;
      hasMore = listClass.isFinished == false;
      // 拼接数据
      List list = listClass.conversationList ?? [];
      List<V2TimConversation?> tempList = list.where((element) => element != null).toList() as List<V2TimConversation?>;
      updateConversationList(tempList, isUpdate: false);
      loadUserFullInfo(tempList);
    }
    // 最后调用父类方法，执行后续操作
    super.loadMoreData(object: object);
  }

  // 更新会话列表
  //
  // newList 会话列表
  Future<void> updateConversationList(List<V2TimConversation?> newList, {bool isUpdate = true}) async {
    try {
      // 未读消息数
      unreadCount.value = 0;

      // 过滤和整理会话列表
      for (V2TimConversation? element in newList) {
        // 版本重点：忽略无效数据，admin、和客服发来的消息
        // 我自己的ID（切换账号时会出现）
        if (element == null ||
            element.userID == null ||
            element.userID == XinDongTencentSingleton.IM_SYSTEM ||
            element.userID == loginUserId) {
          continue;
        }

        // 客服通知
        if (element.userID == XinDongTencentSingleton.instance.customerID) {
          // XinDongMessageInformController.to.updateServiceMessage(count: element.unreadCount ?? 0);
          continue;
        }
        // if (element.userID == XinDongTencentChatSingleton.IM_SYSTEM) {
        //   XinDongMessageInformController.to.updateSystemMessage(count: element.unreadCount ?? 0);
        //   continue;
        // }
        if (element.userID == XinDongTencentSingleton.IM_ADMIN) {
          signalMessageIds.add(element.lastMessage!.msgID!);
          continue;
        }
        // 信令
        if (element.lastMessage != null &&
            XinDongTencentSingleton.instance.isInvitationSignaling(element.lastMessage!)) {
          signalMessageIds.add(element.lastMessage!.msgID!);
          continue;
        }
        // 版本重点：最新都消息被删除（不放入列表，单独抽出）
        // if (element.lastMessage == null) {
        //   continue;
        // }

        String cid = element.conversationID;
        if (conversationList.any((ele) => ele.conversation.conversationID == cid)) {
          for (int i = 0; i < conversationList.length; i++) {
            if (conversationList[i].conversation.conversationID == cid) {
              conversationList[i].conversation = element;
              break;
            }
          }
        } else {
          final addClass = XinDongLiaoTianClass()..conversation = element;
          conversationList.add(addClass);
          // 获取信息
          loadUserFullInfo([element]);
        }
      }

      // 消息对比排序 置顶>时间
      conversationList.sort((left, right) {
        // 置顶优先
        if (left.conversation.isPinned == true && right.conversation.isPinned == false) {
          return -1;
        } else if (left.conversation.isPinned == false && right.conversation.isPinned == true) {
          return 1;
        }
        // 按最新消息倒序
        if (left.conversation.lastMessage != null && right.conversation.lastMessage != null) {
          return right.conversation.lastMessage!.timestamp!.compareTo(left.conversation.lastMessage!.timestamp!);
        }
        // 都没有消息，按草稿时间
        if (left.conversation.lastMessage == null && right.conversation.lastMessage == null) {
          return right.conversation.draftTimestamp!.compareTo(left.conversation.draftTimestamp!);
        }
        if (left.conversation.lastMessage == null) {
          return -1;
        } else if (right.conversation.lastMessage == null) {
          return 1;
        } else {
          return 0;
        }
      });
      V2TimConversation? elementNew;
      conversationList.forEach((element) {
        // 清空指定对话消息未读数
        if (currentConversationID == element.conversation.conversationID) {
          element.conversation.unreadCount = 0;
        }
        unreadCount.value += element.conversation.unreadCount ?? 0;
        try {
          if ((element.conversation.unreadCount ?? 0) > 0) {
            if ((elementNew == null ||
                (elementNew?.lastMessage?.timestamp ?? 0) <= (element.conversation.lastMessage?.timestamp ?? 0))) {
              elementNew = element.conversation;
            }
          }
        } catch (e) {}
      });
      // XinDongMessageSnackbar.instance.show(elementNew);
      update();
    } catch (e) {
      mCatchPrint(e);
    } finally {
      // 删除信令消息
      if (signalMessageIds.isNotEmpty) {
        await TencentImSDKPlugin.v2TIMManager.getMessageManager().deleteMessages(msgIDs: signalMessageIds);
        signalMessageIds.clear();
      }
    }
  }

  // 移除远端和本地会话
  void removeByConversationId(String conversionId) {
    TencentImSDKPlugin.v2TIMManager
        .getConversationManager()
        .deleteConversation(conversationID: conversionId)
        .then((value) {
      if (value.code == 0) {
        conversationList.removeWhere((element) => element.conversation.conversationID == conversionId);
        // 未读消息数
        unreadCount.value = 0;
        for (var element in conversationList) {
          unreadCount.value = unreadCount.value + (element.conversation.unreadCount ?? 0);
        }
        update();
      } else {
        showToast("${value.code} ${value.desc}");
      }
    });
  }

  // 删除所有本地和远端会话
  Future<void> removeAllConversion() async {
    XinDongAlertOptions.show(
      content: "确定清空聊天记录列表吗？\n清空后不可恢复",
      leftName: '取消',
      rightName: "确认清除",
      onTapRight: () async {
        showLoading(maskColor: Colors.transparent);
        for (var model in conversationList) {
          await TencentImSDKPlugin.v2TIMManager
              .getConversationManager()
              .deleteConversation(conversationID: model.conversation.conversationID);
        }
        refreshData();
        hideLoading();
      },
    );
  }

  // 消息标记已读
  Future<bool> markAllUnread() async {
    unreadCount.value = 0;
    showLoading(maskColor: Colors.transparent);
    V2TimCallback? result = await TencentImSDKPlugin.v2TIMManager.getMessageManager().markAllMessageAsRead();
    hideLoading();
    if (result.code == 0) {
      refreshData();
      showToast("全部已读");
      return true;
    }
    return false;
  }

  // 置顶消息
  Future<bool> requestClearC2CMessages(V2TimConversation conversation) async {
    final TIMUIKitConversationController controller = TIMUIKitConversationController();
    controller.model = TUIConversationViewModel();
    V2TimCallback? result = await controller.clearHistoryMessage(conversation: conversation);
    if (result != null && result.code == 0) {
      showToast("已清空");
      return true;
    }
    return false;
  }

  // 置顶消息
  Future<bool> requestPinConversation(V2TimConversation conversation) async {
    final TIMUIKitConversationController controller = TIMUIKitConversationController();
    controller.model = TUIConversationViewModel();
    V2TimCallback result = await controller.pinConversation(
        conversationID: conversation.conversationID, isPinned: !conversation.isPinned!);
    if (result.code == 0) {
      showToast(conversation.isPinned == true ? "取消置顶" : "已置顶");
      return true;
    }
    return false;
  }
}
